
import EventCenter from "../../TFrame/script/helper/EventCenter";
import EventNames from "../EventNames";
import StatusProperties, { RewardType } from "../game/StatusProperties";
import NativeCaller from "../NativeCaller";
import { ActionType } from "../net/Enum";
import ServiceLogic from "../net/ServerLogic";
import CoinSystem from "../system/CoinSystem";
import IAPSystem from "../system/IAPSystem";
import Util from "../../../StartAb/Util";
import ToastHelper from "./ToastHelper";
import WXAD from "../../../StartAb/WXAd";

const { ccclass, property } = cc._decorator;

@ccclass
export default class ShopDialog extends cc.Component {

    //防止多开
    static isShowing = false;
    @property(cc.Label)
    timeLabel: cc.Label = null;

    @property(cc.Button)
    getFreeButton: cc.Button = null;

    _clickBuyButtonNode: cc.Node = null;

    FREE_COIN = 100

    static next_ok_ts = 0;
    static waiting_ms = 30000;

    static show(parent) {
        if(ShopDialog.isShowing == true)
            return
        ShopDialog.isShowing = true;
        cc.assetManager.getBundle("GameAb").load("prefab/Shop", cc.Prefab, (err: Error, pf: cc.Prefab) => {
            if (err) {
                ShopDialog.isShowing = false;
                return console.log(err.message);
            }
            if (parent && parent.isValid) {
                let dialog = cc.instantiate(pf);
                dialog.parent = parent;
            }
        })
    }

    onDestroy() {
        ShopDialog.isShowing = false;
    }

    protected onEnable(): void {
        WXAD.instance.showBanner();
    }

    protected onDisable(): void {
        WXAD.instance.hideBanner();
    }

    start() {
        let designedResolution = cc.Canvas.instance.designResolution;
        this.node.scale = designedResolution.width / 640

        let iapNodeNames = []// ["coin200", "coin500", "coin3000", "AD"]
        iapNodeNames.forEach((name:string)=>{
            let node = this.node.getChildByName("layout")
            if(!node)
                return
            node = node.getChildByName(name);
            node && (node.active = (IAPSystem.IAPEnabled || CC_DEBUG))
        })

        console.log("IAD shopdialog:", !IAPSystem.isAdRemoved(),IAPSystem.IAPEnabled , CC_DEBUG )

        if (ShopDialog.next_ok_ts > Date.now()) {
            this.getFreeButton.interactable = false;
            this.timeLabel.node.active = true;
            this.schedule(this.update0Point2, 0.2);
        }
        EventCenter.on(EventNames.RewardedSuccess, () => {
            EventCenter.emit(EventNames.FlyGetCoinEvent, this.FREE_COIN, this.node.convertToWorldSpaceAR(cc.Vec2.ZERO));
            CoinSystem.addCoin(this.FREE_COIN);
            ShopDialog.next_ok_ts = Date.now() + ShopDialog.waiting_ms   //1分钟
            // FireBaseAPI.logEvent("Event_GetFreeCoin", {"coinhave":CoinSystem.coinInMomory})
            this.timeLabel.node.active = true;
            this.getFreeButton.interactable = false;
            this.updateTimerString();
            this.unschedule(this.update0Point2);
            this.schedule(this.update0Point2, 0.2);
            ServiceLogic.action(ActionType.ActionAdToCoin, {});
            ServiceLogic.action(ActionType.ActionCoinChanged, { "coinhave": CoinSystem.coinInMomory, "beiz": this.FREE_COIN })
        }, this)

        EventCenter.on(EventNames.IAPSuccess, (iapId) => {
            let coinNum = IAPSystem.getIAPCoinNum(iapId);
            if(coinNum > 0) {
                console.log("ISHOP success:" + iapId + "," + coinNum)
                let pt = (this._clickBuyButtonNode && this._clickBuyButtonNode.convertToWorldSpaceAR(cc.Vec2.ZERO)) || this.node.convertToWorldSpaceAR(cc.Vec2.ZERO)
                EventCenter.emit(EventNames.FlyGetCoinEvent, coinNum, pt);
            }

            if(iapId == IAPSystem.AD) {
                ToastHelper.show("Remove Forced Ad Success")
            }
        }, this)
    }

    //AD
    getClick() {
        StatusProperties.rewardType = RewardType.ReqGetFreeCoin;
        NativeCaller.showReward();
    }

    buyClicked(e: cc.Event.EventTouch) {
        let node = e.target as cc.Node;
        console.log("IAD IAP:", node.name, IAPSystem[node.name])
        if(IAPSystem[node.name]) {
            NativeCaller.requestBuy(IAPSystem[node.name])
            this._clickBuyButtonNode = node;
        }
    }

    updateTimerString() {
        let sec = (ShopDialog.next_ok_ts - Date.now()) / 1000;
        let str = Util.secondToStr(sec, false);
        this.timeLabel.string = str;
    }

    update0Point2() {
        if (ShopDialog.next_ok_ts <= Date.now()) {
            this.unschedule(this.update0Point2);
            this.getFreeButton.interactable = true;
            this.timeLabel.node.active = false;
            return;
        }
        this.updateTimerString();
    }
}
